import { identity, USER_IDENTITIES } from './identity.js'
import storage from './storage.js'

// 不同身份的tabBar配置
export const TABBAR_CONFIGS = {
  [USER_IDENTITIES.USER]: [
    {
      text: "测评",
      pagePath: "pages/test/test",
      iconPath: "/static/icon/advice.png",
      selectedIconPath: "/static/icon/advice-selected.png"
    },
    {
      text: "资源",
      pagePath: "pages/resource/resource",
      iconPath: "/static/icon/train.png",
      selectedIconPath: "/static/icon/train_selected.png"
    },
    {
      text: "我的",
      pagePath: "pages/profile/profile",
      iconPath: "/static/icon/my.png",
      selectedIconPath: "/static/icon/my-selected.png"
    }
  ],
  [USER_IDENTITIES.HEALTH_TEAM]: [
    {
      text: "咨询",
      pagePath: "pages/expert_consult_list/expert_consult_list",
      iconPath: "/static/icon/advice.png",
      selectedIconPath: "/static/icon/advice-selected.png"
    },
    {
      text: "资源",
      pagePath: "pages/resource/resource",
      iconPath: "/static/icon/train.png", 
      selectedIconPath: "/static/icon/train_selected.png"
    },
    {
      text: "我的",
      pagePath: "pages/profile/profile",
      iconPath: "/static/icon/my.png",
      selectedIconPath: "/static/icon/my-selected.png"
    }
  ],
  [USER_IDENTITIES.ADMIN]: [
    {
      text: "申请",
      pagePath: "pages/test/test",
      iconPath: "/static/icon/advice.png",
      selectedIconPath: "/static/icon/advice-selected.png"
    },
    {
      text: "资源",
      pagePath: "pages/resource/resource",
      iconPath: "/static/icon/train.png",
      selectedIconPath: "/static/icon/train_selected.png"
    },
    {
      text: "我的",
      pagePath: "pages/profile/profile",
      iconPath: "/static/icon/my.png",
      selectedIconPath: "/static/icon/my-selected.png"
    }
  ]
}

let customTabbarItems = null;

// Helper: get current identity's items
const getTabbarItemsInternal = () => {
  const currentIdentity = identity.getIdentity();
  const base = TABBAR_CONFIGS[currentIdentity] || [];
  if (!customTabbarItems) return base;
  // merge by index
  return base.map((item, index) => ({
    ...item,
    ...(customTabbarItems[index] || {})
  }));
}

/**
 * 根据用户身份更新tabBar
 * @param {number} identity - 用户身份
 * @returns {Promise<boolean>} 更新是否成功
 */
export const updateTabBarByIdentity = async (identity) => {
  const config = TABBAR_CONFIGS[identity];
  if (!config) {
    console.error('未找到对应身份的tabBar配置:', identity);
    return false;
  }
  return true;
}


/**
 * 刷新tabBar（在tabBar页面的onShow中调用）
 * @returns {Promise<boolean>} 刷新是否成功
 */
/**
 * 获取当前tabBar身份
 */
const getCurrentTabIdentity = () => {
  return storage.get('tab_identity') || USER_IDENTITIES.USER;
}

/**
 * 设置当前tabBar身份
 */
const setCurrentTabIdentity = (identity) => {
  storage.setPermanent('tab_identity', identity);
}

/**
 * 初始化tabBar身份（在App启动时调用）
 */
export const initTabIdentity = () => {
  setCurrentTabIdentity(USER_IDENTITIES.USER);
}

export const refreshTabBar = async (forceReload = false) => {
  const currentIdentity = identity.getIdentity();
  const currentTabIdentity = getCurrentTabIdentity();
  
  if (currentIdentity !== currentTabIdentity || forceReload) {
    setCurrentTabIdentity(currentIdentity);
  }
  if (typeof uni !== 'undefined' && uni.$emit) {
    uni.$emit('tabbar:refresh');
  }
  return true;
}

export const getIdentityDefaultTabPage = () => {
  const currentIdentity = identity.getIdentity();
  return "/" + TABBAR_CONFIGS[currentIdentity][0].pagePath;
}

/**
 * 自定义tabbar：获取当前应显示的tabbar项列表
 */
export const getCurrentTabbarItems = () => {
  return getTabbarItemsInternal();
}

/**
 * 自定义tabbar：单项设置（类比 setTabBarItem，但仅作用于自定义组件）
 * @param {number} index
 * @param {{text?: string, pagePath?: string, iconPath?: string, selectedIconPath?: string}} payload
 */
export const setTabbarItem = (index, payload) => {
  const items = getTabbarItemsInternal();
  const next = items.map((it, i) => i === index ? ({ ...it, ...payload }) : it);
  customTabbarItems = next;
  if (typeof uni !== 'undefined' && uni.$emit) {
    uni.$emit('tabbar:refresh');
  }
}

/**
 * 自定义tabbar：切换到tab（统一入口）
 * @param {string} url like "/pages/test/test"
 */
export const switchTab = ({url}) => {
  if (!url) return;
  // Prefer native switchTab when available (requires tabBar config), fallback to reLaunch
  if (typeof uni !== 'undefined' && typeof uni.switchTab === 'function') {
    uni.switchTab({ url, fail: () => {
      if (typeof uni.reLaunch === 'function') {
        uni.reLaunch({ url });
      }
    }});
    return;
  }
  if (typeof uni !== 'undefined' && typeof uni.reLaunch === 'function') {
    uni.reLaunch({ url });
  }
}

/**
 * Hide native tabBar UI if present (hybrid approach)
 */
export const hideNativeTabBar = () => {
  if (typeof uni !== 'undefined' && typeof uni.hideTabBar === 'function') {
    try {
      uni.hideTabBar({ animation: false });
    } catch (_) {}
  }
}

export const tabbar = {
  TABBAR_CONFIGS,
  updateTabBarByIdentity,
  refreshTabBar,
  initTabIdentity,
  getIdentityDefaultTabPage,
  getCurrentTabbarItems,
  setTabbarItem,
  switchTab,
  hideNativeTabBar
}

export default tabbar;